﻿using NPOI.HSSF.UserModel;
using OMG.Fill.Mulberry.Model.Ent;
using OMG.Fill.Mulberry.Service;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Http;
namespace OMG.Fill.Mulberry.Model.UI.Controllers
{
    public class MulSilkwormFieldController : ApiController
    {
        MulSilkwormFieldServices mulSilkwormFieldServices = new MulSilkwormFieldServices();
        ReportServices reportServices = new ReportServices();
        DictServices dict = new DictServices();
        //[ApiActionAuthorize("获取桑蚕种场生产经营情况调查表分页列表对象操作")]
        //[ApiActionException]
        public Pager<List<MulSilkwormFieldEntity>> PostPageList(MulSilkwormFieldQuery query)
        {
            return mulSilkwormFieldServices.GetPageList(query);
        }
        //[ApiActionAuthorize("新增桑蚕种场生产经营情况调查表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Post(MulSilkwormFieldEntity model) {
            return mulSilkwormFieldServices.AddInfo(model);
        }
        //[ApiActionAuthorize("修改桑蚕种场生产经营情况调查表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Put(MulSilkwormFieldEntity model)
        {
            return mulSilkwormFieldServices.UpdateInfo(model);
        }
        //[ApiActionAuthorize("删除桑蚕种场生产经营情况调查表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Delete(string id)
        {
            return mulSilkwormFieldServices.DeleteInfo(id);
        }
        //[ApiActionAuthorize("获取桑蚕种场生产经营情况调查表指定对象操作")]
        //[ApiActionException]
        public ResResult<MulSilkwormFieldEntity> Get(string id)
        {
            return mulSilkwormFieldServices.GetModel(id);
        }
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream Method(MulNowModel model)
        {
            model.FillInYear = dict.GetKey(model.FillInYear);
            string ReportId = reportServices.GetReportId(model.ReportCode, model.AreaCode, model.FillInYear);
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\Excel.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("MulSilkwormField") as HSSFSheet;//读取模板所在sheet位置
            ResResult<List<MulSilkwormFieldEntity>> pagelist = mulSilkwormFieldServices.GetList(ReportId);//数据获取

            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式

            for (var i = 0; i < pagelist.model.Count; i++)
            {
                HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 3);
                datarow.CreateCell(0).SetCellValue(pagelist.model[i].PersonalTotal == null ? "" : pagelist.model[i].PersonalTotal.ToString());
                datarow.CreateCell(1).SetCellValue(pagelist.model[i].KJRYNum == null ? "" : pagelist.model[i].KJRYNum.ToString());
                datarow.CreateCell(2).SetCellValue(pagelist.model[i].GJZCNum == null ? "" : pagelist.model[i].GJZCNum.ToString());
                datarow.CreateCell(3).SetCellValue(pagelist.model[i].SCYFMJ == null ? "" : pagelist.model[i].SCYFMJ.ToString());
                datarow.CreateCell(4).SetCellValue(pagelist.model[i].ZYSYMJ == null ? "" : pagelist.model[i].ZYSYMJ.ToString());
                datarow.CreateCell(5).SetCellValue(pagelist.model[i].SCZCL_YZ == null ? "" : pagelist.model[i].SCZCL_YZ.ToString());
                datarow.CreateCell(6).SetCellValue(pagelist.model[i].SCZCL_ZJ == null ? "" : pagelist.model[i].SCZCL_ZJ.ToString());
                datarow.CreateCell(7).SetCellValue(pagelist.model[i].CZXS_YZ == null ? "" : pagelist.model[i].CZXS_YZ.ToString());
                datarow.CreateCell(8).SetCellValue(pagelist.model[i].CZXS_ZJ == null ? "" : pagelist.model[i].CZXS_ZJ.ToString());
                datarow.CreateCell(9).SetCellValue(pagelist.model[i].FixedAssets == null ? "" : pagelist.model[i].FixedAssets.ToString());
                datarow.CreateCell(10).SetCellValue(pagelist.model[i].MulSilkwormProduct == null ? "" : pagelist.model[i].MulSilkwormProduct.ToString());
                datarow.CreateCell(11).SetCellValue(pagelist.model[i].Cost == null ? "" : pagelist.model[i].Cost.ToString());
                datarow.CreateCell(12).SetCellValue(pagelist.model[i].Profit == null ? "" : pagelist.model[i].Profit.ToString());
                datarow.CreateCell(13).SetCellValue(pagelist.model[i].Remark == null ? "" : pagelist.model[i].Remark.ToString());
                datarow.GetCell(0).CellStyle = style;
                datarow.GetCell(1).CellStyle = style;
                datarow.GetCell(2).CellStyle = style;
                datarow.GetCell(3).CellStyle = style;
                datarow.GetCell(4).CellStyle = style;
                datarow.GetCell(5).CellStyle = style;
                datarow.GetCell(6).CellStyle = style;
                datarow.GetCell(7).CellStyle = style;
                datarow.GetCell(8).CellStyle = style;
                datarow.GetCell(9).CellStyle = style;
                datarow.GetCell(10).CellStyle = style;
                datarow.GetCell(11).CellStyle = style;
                datarow.GetCell(12).CellStyle = style;
                datarow.GetCell(13).CellStyle = style;
            }
            sheet.CopyTo(workbook, "Sheet1", true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }

        /// <summary>
        /// 导出下载响应
        /// </summary>
        /// <param name="ReportCode"></param>
        public void GetExcelData(string ReportCode, string FillInYear, string AreaCode)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            MulNowModel model = new MulNowModel();
            model.AreaCode = AreaCode;
            model.FillInYear = FillInYear;
            model.ReportCode = ReportCode;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = model.FillInYear +AreaName+ "全年桑蚕种场生产经营情况调查表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            curContext.Response.BinaryWrite(Method(model).GetBuffer());
            curContext.Response.End();
        }

        public ResResult<List<MulSilkwormFieldInfoModel>> PostStatsList(MulNowModel model)
        {
            return mulSilkwormFieldServices.GetMulSFIList(model);
        }

        public void GetStatsExcelData(string FillInYear, string AreaCode, string Status)
        {
            MulNowModel model = new MulNowModel();
            model.FillInYear = FillInYear;
            model.AreaCode = AreaCode;
            model.Status = Status;
            //string ProvinceCode = "530000000000";
            AreaServices area = new AreaServices();
            List<MulSilkwormFieldInfoModel> list = new List<MulSilkwormFieldInfoModel>();
            if (!string.IsNullOrEmpty(model.AreaCode))
            {
                var listMulArea = mulSilkwormFieldServices.GetMulSFIList(model);
                list = listMulArea.model;
            }
            //string AreaName = area.GetByCodeModel(model.AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = "";
            if (AreaCode != "530000000000")
            {
                string Name = area.GetByCodeModel(AreaCode).model.Name;
                strFileName = FillInYear + Name + "蚕种场生产经营情况调查表.xls";
            }
            else
            {
                strFileName = FillInYear + "全省蚕种场生产经营情况调查表.xls";
            }
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            curContext.Response.BinaryWrite(MethodStats(list).GetBuffer());
            curContext.Response.End();
        }

        public MemoryStream MethodStats(List<MulSilkwormFieldInfoModel> list)
        {
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\ExcelStats.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("MulSilkwormField") as HSSFSheet;//读取模板所在sheet位置
            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            var styleAreaOne = Common.GetOneAreaCellStyle(templateBook, style);
            var styleAreaInt = Common.GetIntAreaCellStyle(templateBook, style);
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 3);
                    datarow.CreateCell(0).SetCellValue(list[i].year == null ? "" : list[i].year.ToString());
                    datarow.CreateCell(1).SetCellValue(list[i].Name == null ? "" : list[i].Name.ToString());
                    datarow.CreateCell(2).SetCellValue(list[i].PersonalTotal == null ? 0 :Convert.ToDouble( list[i].PersonalTotal));
                    datarow.CreateCell(3).SetCellValue(list[i].KJRYNum == null ? 0 : Convert.ToDouble( list[i].KJRYNum));
                    datarow.CreateCell(4).SetCellValue(list[i].GJZCNum == null ? 0 : Convert.ToDouble( list[i].GJZCNum));
                    datarow.CreateCell(5).SetCellValue(list[i].SCYFMJ == null ? 0.0 : Convert.ToDouble( list[i].SCYFMJ));
                    datarow.CreateCell(6).SetCellValue(list[i].ZYSYMJ == null ? 0.0 : Convert.ToDouble( list[i].ZYSYMJ));
                    datarow.CreateCell(7).SetCellValue(list[i].SCZCL_YZ == null ? 0.0 : Convert.ToDouble( list[i].SCZCL_YZ));
                    datarow.CreateCell(8).SetCellValue(list[i].SCZCL_ZJ == null ? 0.0 : Convert.ToDouble( list[i].SCZCL_ZJ));
                    datarow.CreateCell(9).SetCellValue(list[i].CZXS_YZ == null ? 0.0 : Convert.ToDouble( list[i].CZXS_YZ));
                    datarow.CreateCell(10).SetCellValue(list[i].CZXS_ZJ == null ? 0.0 : Convert.ToDouble( list[i].CZXS_ZJ));
                    datarow.CreateCell(11).SetCellValue(list[i].FixedAssets == null ? 0.0 : Convert.ToDouble( list[i].FixedAssets));
                    datarow.CreateCell(12).SetCellValue(list[i].MulSilkwormProduct == null ? 0.0 : Convert.ToDouble( list[i].MulSilkwormProduct));
                    datarow.CreateCell(13).SetCellValue(list[i].Cost == null ? 0.0 : Convert.ToDouble( list[i].Cost));
                    datarow.CreateCell(14).SetCellValue(list[i].Profit == null ? 0.0 : Convert.ToDouble( list[i].Profit));
                    datarow.CreateCell(15).SetCellValue(list[i].Remark == null ? "" : list[i].Remark.ToString());
                    for (var j = 0; j < 16; j++)
                    {
                        datarow.GetCell(j).CellStyle = styleAreaOne;
                        if(j==2||j==3||j==4)
                        {
                            datarow.GetCell(j).CellStyle = styleAreaInt;
                        }
                    }
                }
            }
            sheet.CopyTo(workbook, "Sheet1", true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
    }
}